import {Component, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {ActivatedRoute, Router} from '@angular/router';
import {UtilityService} from '../../../../service/utils.service';
import {appConfig} from '../../../../service/common';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {AppConfigModule} from "../../../../service/common.module";
import {CommondictServe} from '../../../../service/commonDict';
import {PlatformLocation} from '@angular/common'

@Component({
  selector: 'app-app-config',
  templateUrl: './app-config.component.html',
})
export class AppConfigComponent implements OnInit {

    constructor(
        private http: _HttpClient,
        private router: Router,
        private activatedRoute: ActivatedRoute, // 注入路由，接收到参数
        private modal: NzModalService,
        private nznot: NzNotificationService,
        private utilityService: UtilityService,
        private commondict: CommondictServe,
        location: PlatformLocation
    ) {
    }

    // 绑定类
    appConfigitem: AppConfigModule = new AppConfigModule();
    appConfigAdd: AppConfigModule = new AppConfigModule();
    configTitle: any; // 默认的修改按钮的名称
    isEdit: boolean; // 是否是修改
    configAppTitle: string; // 弹出框标题
    page: any; // 翻页方法
    appGuid: string; // 父组件传过来的guid
    data: any[] = []; // 表格数据
    total: number; // 总数数据
    modalVisible = false; // 弹出框默认false
    loading = false; // 弹出框默认false
    buttons = [
        {key: 'add', value: '新增个性化配置', buttonCode: appConfig.funcObject.app.addConfig}
    ]
    selectedRows: any; // 总数
    // 表格表头
    headerData = [  // 配置表头内容
        { value: '配置类型', key: 'configType', isclick: false },
        { value: '配置名', key: 'configName', isclick: false },
        { value: '配置值字典', key: 'dictName', isclick: false },
        { value: '配置风格', key: 'configStyle', isclick: false },
        { value: '默认配置值', key: 'valueName', isclick: false },
        { value: '是否启用', key: 'enabled', isclick: false },
        { value: '显示顺序', key: 'displayOrder', isclick: false },
        { value: '配置描述说明', key: 'configDesc', isclick: false },
    ];

    // 枚举值
    configType: any; // 配置类型
    configDict = []; // 配置值字典
    configValue: any; // 配置值字典默认值
    index = 0; // 查询所有业务字典需要的
    configStyle: any; // 配置风格
    isopen: any; // 是否启用
    pageIndex = 1; // 当前页数
    expandForm = false;
       ngOnInit() {
        this.appGuid = this.activatedRoute.snapshot.params.id; // 拿到父组件传过来的组织机构的guid来进行操作
        this.configTitle = {value: '修改', buttonCode: appConfig.funcObject.app.editConfig}
        // 枚举值绑定
        this.isopen = appConfig.Enumeration.dictYon;
        this.configType = appConfig.Enumeration.systemType;
        this.configStyle = appConfig.Enumeration.fromType;
        this.getData();
        this.dictQueryKey()
        this.generateFakeData();
    }



    // 所有业务字典,不分页
    generateFakeData() {
        this.page = {
            page: {
                current: this.index,
                size: 10000, // 先写死长度
            }
        };
        // 调用服务来获取列表节点操作
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.sysDictList ,  this.page)
            .subscribe(
                (val) => {
                    for (let i = 0; i < val.result.records.length; i++) {
                        this.configDict.push(val.result.records[i]);
                        this.index++;
                    }
                });
    }

    // selete监听方法
    checkSelect(guid) {
        this.appConfigAdd.configValue = null;
        // 根据key查询对应业务字典项
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.queryListByDictId + '/' + guid)
            .subscribe(
                (val) => {
                    if (val.result.length > 0) {
                        this.configValue = val.result;
                    } else {
                        this.appConfigAdd.configValue = null;
                        this.configValue = [];
                    }


                }
            );
    }





    // 根据key查询业务字典
    dictQueryKey() {
        this.commondict.queryDictKey(appConfig.dictKeyList.dictType)
            .subscribe((val) => {
                this.configType = val.result;
            })

        this.commondict.queryDictKey(appConfig.dictKeyList.styleColor)
            .subscribe((val) => {
                this.configStyle = val.result;
            })


        this.commondict.queryDictKey(appConfig.dictKeyList.dictYon)
            .subscribe((val) => {
                this.isopen = val.result;
            })
    }

    // 初始化方法
    getData(option?) {
        if (option) {
            this.pageIndex = 1;
        }
        this.page = {
            condition: this.objJson, // 搜索内容
            page: {
                current: this.pageIndex,
                size: this.appConfigitem.size,
            }
        };
        /*for (let i = 0; i < this.data.length; i++ ) {
            this.data[i].buttonData = [{key: 'dels', value: '删除', if: false}];
        }*/

        this.utilityService.postData(appConfig.serverUrl + appConfig.API.listByAppId + '/' + this.appGuid, this.page)
            .subscribe(
                (val) => {
                    console.log()
                    for (let i = 0; i < val.result.records.length; i++ ) {
                        if(val.result.records[i].configType === 'a') {
                            val.result.records[i].configType = '应用';
                        } else {
                            val.result.records[i].configType = '系统';
                        }

                        if(val.result.records[i].enabled === 'N') {
                            val.result.records[i].enabled = '否';
                        } else {
                            val.result.records[i].enabled = '是';
                        }

                        val.result.records[i].buttonData = [{key: 'dels', value: '删除', if: false}];
                    }
                    this.data = val.result.records;
                    this.total = val.result.total;
                }
            );
    }

    addHandler(event) {
        console.log(event)
        if (event === 'add') {
            this.configAppTitle = '新增个性化配置';
            this.appConfigAdd = new AppConfigModule();
            this.isEdit = false;
        } else { // 代表修改，把修改的内容传递进去，重新渲染
            if(event.configType === '应用') {
                event.configType = 'a'
            } else {
                event.configType = 's'
            }

            if(event.enabled === '是') {
                event.isopen = 'Y'
            } else {
                event.isopen = 'N'
            }

            this.configAppTitle = '修改个性化配置';
            this.isEdit = true;
            this.appConfigAdd = event;
        }
        this.modalVisible = true;
    }

    // 翻页
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }

    // 删除的方法
    deleatData(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除该个性化配置吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                // 模拟接口
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.acAppConfig + '/' + event)
                    .subscribe(
                        (val) => {
                            // 修改成功只和的处理逻辑
                            this.nznot.create('success', val.msg , val.msg);
                            if ( !(( this.total - 1) % 10)) {
                                // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                                this.appConfigitem.pi -- ;
                            }
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.getData();
            }
        });
    }


    // 批量删除的方法
    configbatchDel(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '条个性化配置吗吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    deleteList: delarray
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.appConfigbathDel, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData();
                            this.selectedRows = []
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.selectedRows = []
                this.getData();
            }
        });
    }


    // 按钮点击事件
    buttonEvent(event) {
        if(event.names.key === 'dels') {
            this.deleatData(event.guid); // 删除方法
        }
    }



    objJson = {};
    // 搜索框
    search() {
        this.objJson = this.appConfigitem;
        this.getData(this.appConfigitem);
    }

    reset() {
        this.appConfigitem = new AppConfigModule(); // 重置
        this.objJson = {};
        this.getData();
    }

    save(item) {
        const jsonObj = this.appConfigAdd;
        jsonObj.guidApp = this.appGuid;
        // 新增功能、修改功能逻辑
        if (!this.isEdit) {  // 新增的业务逻辑
            this.utilityService.postData(appConfig.serverUrl + appConfig.API.acAppConfig, jsonObj)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                        this.getData();
                    }
                );
            this.modalVisible = false;
        } else if (this.isEdit) {
            // 修改的保存逻辑
            this.utilityService.putData(appConfig.serverUrl + appConfig.API.acAppConfig, jsonObj)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                        this.getData();
                    });
            this.modalVisible = false;
        }
    }

}
